<template>
  <div>
    <t-card class="list-card-container">
      <!-- 操作按钮 -->
      <t-row justify="space-between">
        <div class="left-operation-container">
          <t-button @click="handleSetupContract"> 新建 </t-button>
          <t-button
            variant="base"
            theme="default"
            @click="handleSearch"
          >
            搜索
          </t-button>
        </div>
      </t-row>
      <!-- 列表 -->
      <div class="table-container">
        <el-table
          :data="data"
          style="width: 100%"
          :height="tableHeight"
        >
          <el-table-column
            v-for="(item, index) in columns"
            v-if="item.colKey !== 'op' && item.colKey !== 'projectStatus' && item.colKey !== 'priority'"
            :prop="item.colKey"
            :label="item.title"
            width="200px"
          >
          </el-table-column>
          <el-table-column
            v-for="(item, index) in columns"
            v-if="item.colKey == 'projectStatus'"
            :prop="item.colKey"
            :label="item.title"
          >
            <template slot-scope="slotProps">
              <div v-if="slotProps.row.projectStatus == 0">
                正常
              </div>
              <div v-else-if="slotProps.row.projectStatus == 1">
                暂停
              </div>
            </template>
          </el-table-column>
          <el-table-column
            v-for="(item, index) in columns"
            v-if="item.colKey == 'priority'"
            :prop="item.colKey"
            :label="item.title"
          >
            <template slot-scope="slotProps">
              <div v-if="slotProps.row.priority == 0">
                高
              </div>
              <div v-else-if="slotProps.row.priority == 1">
                中
              </div>
              <div v-else>
                低
              </div>
            </template>
          </el-table-column>
          <el-table-column
            v-for="(item, index) in columns"
            v-if="item.colKey == 'op'"
            :prop="item.colKey"
            :label="item.title"
            width="200px"
            fixed="right"
          >
            <template slot-scope="slotProps">
              <a
                class="t-button-link"
                @click="queryId(slotProps)"
              >编辑</a>
              <a
                class="t-button-link"
                @click="handleClickDelete(slotProps)"
              >删除</a>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :hide-on-single-page="pagination.total <= 0"
          :current-page="pagination.defaultCurrent"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pagination.defaultPageSize"
          layout="total,->, sizes, prev, pager, next, jumper"
          :total="pagination.total"
        >
        </el-pagination>
      </div>
    </t-card>
    <!-- 弹窗 -->
    <t-dialog
      header="确认删除当前所选内容？"
      :visible.sync="confirmVisible"
      :on-cancel="onCancel"
      @confirm="onConfirmDelete"
    />
    <!-- 新增弹窗 -->
    <t-dialog
      header="人员信息"
      :visible="showModal"
      :on-close="funClose"
      :on-confirm="funConfirm"
    >
      <div slot="body">
        <t-form
          :data="formData"
          :rules="rules"
          ref="form"
          @reset="onReset"
          @submit="onSubmit"
        >
          <t-form-item
            label="ceshi"
            help="这里可以展示一段说明文字"
          >
          </t-form-item>
          <t-form-item
            label="项目名字"
            help="这里可以展示一段说明文字"
            name="projectName"
          >
            <t-input
              v-model="formData.projectName"
              placeholder="请输入项目名字"
            />
          </t-form-item>
          <t-form-item
            label="项目联系人"
            name="projectContacts"
          >
            <t-input
              v-model="formData.projectContacts"
              placeholder="项目联系人"
            />
          </t-form-item>
          <t-form-item
            label="项目联系人电话"
            name="phone"
          >
            <t-input
              v-model="formData.phone"
              placeholder="项目联系人电话"
            />
          </t-form-item>
          <t-form-item
            label="创建者"
            name="createBy"
          >
            <t-input
              v-model="formData.createBy"
              placeholder="请输入创建者"
            />
          </t-form-item>
          <t-form-item
            label="创建时间"
            name="createTime"
          >
            <t-date-picker
              enable-time-picker
              allow-input
              clearable
              format="YYYY-MM-DD hh:mm:ss"
              v-model="formData.createTime"
              placeholder="请输入创建时间"
            />
          </t-form-item>
          <t-form-item
            label="更新者"
            name="updateBy"
          >
            <t-input
              v-model="formData.updateBy"
              placeholder="请输入更新者"
            />
          </t-form-item>
          <t-form-item
            label="更新时间"
            name="updateTime"
          >
            <t-date-picker
              enable-time-picker
              allow-input
              clearable
              format="YYYY-MM-DD hh:mm:ss"
              v-model="formData.updateTime"
              placeholder="请输入更新时间"
            />
          </t-form-item>
          <t-form-item
            label="备注"
            name="remark"
          >
            <t-input
              v-model="formData.remark"
              placeholder="请输入备注"
            />
          </t-form-item>
          <t-form-item
            label="项目状态"
            name="projectStatus"
          >
            <t-radio-group v-model="formData.projectStatus">
              <t-radio value="0">正常</t-radio>
              <t-radio value="1">暂停</t-radio>
            </t-radio-group>
          </t-form-item>
          <t-form-item
            label="所属部门"
            name="department"
          >
            <t-input
              v-model="formData.department"
              placeholder="请输入所属部门"
            />
          </t-form-item>
          <t-form-item
            label="项目优先级"
            name="priority"
          >
            <t-radio-group v-model="formData.priority">
              <t-radio value="0">高</t-radio>
              <t-radio value="1">中</t-radio>
              <t-radio value="2">底</t-radio>
            </t-radio-group>
          </t-form-item>
          <t-form-item
            label="逻辑删除"
            name="deleted"
          >
            <t-input
              v-model="formData.deleted"
              placeholder="请输入逻辑删除"
            />
          </t-form-item>
          <t-form-item
            label="项目金额"
            name="amount"
          >
            <t-input-number
              v-model="formData.amount"
              placeholder="请输入项目金额"
            />
          </t-form-item>
        </t-form>
      </div>
    </t-dialog>
    <!-- 文件上传弹窗 -->
    <t-dialog
      header="上传文件"
      :visible="showUploadModal"
      :on-close="funUploadClose"
      :on-confirm="funUploadConfirm"
    >
      <div
        slot="body"
        style="width: 100%;display: flex;justify-content: center;"
      >
        <file-upload
          v-model="imgUrl2"
          upload-type="minio"
          :limit="1"
          :is-picture-card="false"
          :is-show-tip="false"
          biz-path="portal/oo-csc-upp-system-atom"
        />
      </div>
    </t-dialog>
  </div>
</template>
<script lang="ts">
import Vue from "vue";
import { SearchIcon } from "tdesign-icons-vue";
import Trend from "@/components/mainEntrance/trend/index.vue";
import { prefix } from "@/config/global";
import { selectPage, queryList, queryId, saveOrUpdate, deleteFun } from "@/api/exampleApi/api.js";
import { CONTRACT_STATUS, CONTRACT_STATUS_OPTIONS, CONTRACT_TYPES, CONTRACT_PAYMENT_TYPES } from "@/constants";
import dayjs from "dayjs";
import FileUpload from "@/components/mainEntrance/FileUpload/index.vue";
// import { downFile } from "@/components/upload/utils/file.ts";

export default Vue.extend({
  name: "ListBase",
  components: {
    SearchIcon,
    Trend,
    FileUpload
  },
  filters: {
    filterStatus(key) {
      let value = "";
      switch (key) {
        case 0:
          value = "正常";
          break;
        case 1:
          value = "暂停";
          break;
        default:
          break;
      }
      key = value;
      return key;
    }
  },
  data() {
    const INITIAL_DATA = {
      projectId: "",
      projectName: "",
      projectContacts: "",
      phone: "",
      createBy: "",
      createTime: dayjs().format("YYYY-MM-DD hh:mm:ss"),
      updateBy: "",
      updateTime: dayjs().add(7, 'days').format("YYYY-MM-DD hh:mm:ss"),
      remark: "",
      projectStatus: "",
      department: "",
      priority: "",
      deleted: 0,
      amount: 0
    };
    return {
      value1: ['选项1', '选项2'],
      options: [{
        value: '选项1',
        label: '黄金糕'
      }, {
        value: '选项2',
        label: '双皮奶'
      }, {
        value: '选项3',
        label: '蚵仔煎'
      }, {
        value: '选项4',
        label: '龙须面'
      }, {
        value: '选项5',
        label: '北京烤鸭'
      }],
      thCss: "custom-th-class",
      tableHeight: window.innerHeight - 180,
      CONTRACT_STATUS,
      CONTRACT_STATUS_OPTIONS,
      CONTRACT_TYPES,
      CONTRACT_PAYMENT_TYPES,
      prefix,
      dataLoading: false,
      data: [],
      selectedRowKeys: [],
      value: "first",

      formData: { ...INITIAL_DATA },
      // FormItem.rules 优先级大于 Form.rules
      rules: {
        account: [
          {
            required: true,
            message: "姓名必填",
            type: "error",
            trigger: "blur"
          },
          // trigger 默认为 'change'
          { required: true, message: "姓名必填", type: "error" },
          { whitespace: true, message: "姓名不能为空" },
          {
            min: 2,
            message: "至少需要两个字符，一个中文等于两个字符",
            type: "warning",
            trigger: "blur"
          },
          {
            max: 10,
            message: "姓名字符长度超出",
            type: "warning",
            trigger: "blur"
          }
        ],
        description: [
          {
            validator: val => val.length >= 5,
            message: "至少 5 个字，中文长度等于英文长度",
            type: "warning"
          },
          {
            validator: val => val.length < 20,
            message: "不能超过 20 个字，中文长度等于英文长度",
            type: "warning"
          }
        ],
        age: [{ required: true, message: "年龄必填", type: "error" }],
        region: [{ required: true, message: "籍贯必填", type: "error" }],

        password: [
          { required: true, message: "密码必填", type: "error" },
          { len: 8, message: "请输入 8 位密码", type: "warning" },
          { pattern: /[A-Z]+/, message: "密码必须包含大写字母", type: "warning" }
        ],
        college: [{ required: true, message: "此项必填" }],
        email: [
          { required: true, message: "邮箱必填" },
          { email: { ignore_max_length: true }, message: "请输入正确的邮箱地址" }
        ],
        gender: [{ required: true, message: "性别必填" }],
        course: [
          { required: true, message: "课程必填" },
          { validator: (val) => val.length <= 2, message: "最多选择 2 门课程", type: "warning" }
        ],
        hobby: [{ required: true, message: "爱好必填", type: "error" }],
        "content.url": [
          { required: true, message: "个人网站必填" },
          {
            url: {
              protocols: ["http", "https", "ftp"],
              require_protocol: true
            },
            message: "请输入正确的个人主页"
          }
        ]
      },
      columns: [
        // {
        //   colKey: "projectId",
        //   type: "multiple",
        //   width: 100,
        //   fixed: "left",
        //   className: ({ row }) => {
        //     return 'cell-css';
        //   },
        // },
        {
          title: "项目名字",
          align: "left",
          width: 200,
          ellipsis: true,
          colKey: "projectName",
        },
        {
          title: "项目联系人",
          width: 200,
          ellipsis: true,
          colKey: "projectContacts"
        },
        {
          title: "项目联系人电话",
          width: 200,
          ellipsis: true,
          colKey: "phone"
        },
        {
          title: "创建者",
          width: 200,
          ellipsis: true,
          colKey: "createBy"
        },
        {
          title: "创建时间",
          width: 200,
          ellipsis: true,
          colKey: "createTime"
        },
        {
          title: "更新者",
          width: 200,
          ellipsis: true,
          colKey: "updateBy"
        },
        {
          title: "更新时间",
          width: 200,
          ellipsis: true,
          colKey: "updateTime"
        },
        {
          title: "备注",
          width: 200,
          ellipsis: true,
          colKey: "remark"
        },
        {
          title: "项目状态",
          width: 200,
          ellipsis: true,
          colKey: "projectStatus"
        },
        {
          title: "所属部门",
          width: 200,
          ellipsis: true,
          colKey: "department"
        },
        {
          title: "项目优先级",
          width: 200,
          ellipsis: true,
          colKey: "priority"
        },
        {
          title: "逻辑删除",
          width: 200,
          ellipsis: true,
          colKey: "deleted"
        },
        {
          title: "项目金额",
          width: 200,
          ellipsis: true,
          colKey: "amount"
        },
        {
          align: "left",
          fixed: "right",
          width: 200,
          colKey: "op",
          title: "操作",
          className: () => 'cell-css',
        }
      ],
      rowKey: "index",
      tableLayout: "fixed",
      verticalAlign: "top",
      hover: true,
      // 与pagination对齐
      pagination: {
        defaultPageSize: 20,
        total: 0,
        defaultCurrent: 1
      },
      searchValue: "",
      confirmVisible: false,
      showModal: false,
      exportVisible: false,
      editData: null,//通过 id 查询项目数据 编辑数据
      deleteIdx: -1,
      showUploadModal: false,//文件上传弹窗
      imgUrl1: "", // 引入图片方法一
      imgUrl2: undefined, // 引入图片方法二
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        dictName: undefined,
        dictType: undefined,
        status: undefined,
        beginTime: undefined,
        endTime: undefined
      },// 导出参数
    };
  },
  computed: {
    confirmExport() {
      return `导出所选信息`;
    },
    offsetTop() {
      return this.$store.state.setting.isUseTabsRouter ? 48 : 0;
    }
  },
  mounted() {
    this.selectPage();
  },

  methods: {
    selectChange(value) {
      console.log('value', value);
    },
    handleSizeChange(val) {
      this.pagination.defaultPageSize = val;
      this.selectPage();
    },
    handleCurrentChange(val) {
      this.pagination.defaultCurrent = val;
      this.selectPage()
    },
    // 列表显示
    selectPage() {
      try {
        this.dataLoading = true;
        const param = {
          page: this.pagination.defaultCurrent,
          limit: this.pagination.defaultPageSize
        };
        selectPage(param).then(res => {
          if (res.data.code == 200) {
            this.data = res.data.data.list;
            this.pagination.total = res.data.data.total;
            this.dataLoading = false;
          } else {
            this.data = []
            this.$message.error({ content: "请重新搜索!", placement: 'top' },)
            this.dataLoading = false;
          }
        });
      } catch (error) {
        this.dataLoading = false;
        console.warn('接口提示', error);
      }
    },
    handlePageChange(pageInfo) {
      this.pagination.defaultCurrent = pageInfo.current;
      this.pagination.defaultPageSize = pageInfo.pageSize;
      this.selectPage()
    },
    // 通过id查询详情
    queryId(value) {
      try {
        const param = {
          projectId: value.row.projectId
        }
        queryId(param).then(res => {
          if (res.data.code == 200) {
            this.editData = null
            this.editData = res.data.data
            this.showModal = true
            this.formData = res.data.data
          } else {
            this.$message.error({ content: "请重新点击编辑按钮!", placement: 'top' },)
          }
        })
      } catch (error) {
        this.$message.error({ content: "请重新点击编辑按钮!", placement: 'top' },)
      }
    },
    saveOrUpdate() {
      try {
        const param = this.formData
        saveOrUpdate(param).then(res => {
          this.showModal = false;
          if (res.data.code == 200) {
            this.$message.success({ content: '保存成功!', placement: 'top' },)
            this.selectPage()
          } else {
            this.$message.error({ content: "请重新点击保存按钮!", placement: 'top' },)
          }
        })
      } catch (error) {
        this.$message.error({ content: "请重新点击保存按钮!", placement: 'top' },)
        this.showModal = false;
      }
    },
    // 文件下载
    handleDownload() {
      this.download(
        "system/dict/type/export",
        {
          ...this.queryParams
        },
        `type_${new Date().getTime()}.xlsx`
      );
    },
    handleUpload() {
      this.showUploadModal = true;
    },
    // 文件上传关闭
    funUploadClose() {
      this.imgUrl2 = undefined;
      this.showUploadModal = false;
    },
    // 文件上传确认
    funUploadConfirm() {
      this.$message.success("文件上传成功");
      this.imgUrl2 = undefined;
      this.showUploadModal = false;
    },
    deleteFun() {
      try {
        const param = {
          projectId: this.deleteIdx
        }
        deleteFun(param)
          .then(res => {
            if (res.data.code == 200) {
              this.confirmVisible = false;
              this.$message.success("删除成功");
              this.resetIdx();
              this.selectPage()
            } else {
              this.$message.error({ content: "请重新点击删除按钮!", placement: 'top' },)
            }
          })
      } catch (error) {
        this.$message.error({ content: "请重新点击删除按钮!", placement: 'top' },)
        this.confirmVisible = false;
      }


    },
    // 关闭弹窗
    funClose() {
      this.showModal = false;
    },
    // 新增弹窗
    funConfirm() {
      this.saveOrUpdate()
    },
    // 重置校验
    onReset() {
      this.$message.success("重置成功");
    },
    // 新增提交
    onSubmit({ validateResult, firstError }) {
      if (validateResult === true) {
        this.$message.success("提交成功");
        this.showModal = false;
      } else {
        this.$message.warning(firstError);
      }
    },
    handleClear() {
      this.$refs.form.clearValidate();
    },

    getContainer() {
      return document.querySelector(".tdesign-starter-layout");
    },
    // 编辑
    handleClickDetail() {
      this.showModal = true;
    },
    // 导出
    handleExport() {
      this.exportVisible = true;
    },
    // 关闭导出
    exportCancel() {
      this.exportVisible = false;
    },
    // 确认都出
    onConfirmExport() {
      this.exportVisible = false;
    },
    // 搜索按钮
    handleSearch() {
      // console.log("搜索列表");
      this.selectPage();
    },
    handleSetupContract() {
      this.formData = {
        projectId: "",
        projectName: "",
        projectContacts: "",
        phone: "",
        createBy: "",
        createTime: dayjs().format("YYYY-MM-DD hh:mm:ss"),
        updateBy: "",
        updateTime: dayjs().add(7, 'days').format("YYYY-MM-DD hh:mm:ss"),
        remark: "",
        projectStatus: "",
        department: "",
        priority: "",
        deleted: 0,
        amount: ""
      }
      this.showModal = true;
    },
    // 删除
    handleClickDelete(row) {
      this.deleteIdx = row.row.projectId;
      this.confirmVisible = true;
    },
    // 确认删除
    onConfirmDelete() {
      // 真实业务请发起请求
      this.deleteFun()

    },
    onCancel() {
      this.resetIdx();
    },
    resetIdx() {
      this.deleteIdx = null;
    }
  }
});
</script>
<style>
.t-table--column-fixed .t-table__cell--fixed-right {
  z-index: 999;
  background-color: #fff;
}
</style>

<!-- <style scoped>
.myTable>>>.t-pagination__number.t-is-current {
  /* background-color: green; */
}

.custom-th-class {
  background-color: #fff;
}

.cell-css {
  background-color: #fff;
  z-index: 999;
}
</style> -->

<style lang="less" scoped>
@import "@/style/variables";

.payment-col {
  display: flex;

  .trend-container {
    display: flex;
    align-items: center;
    margin-left: 8px;
  }
}

.left-operation-container {
  padding: 0 0 6px;
  margin-bottom: 16px;

  .selected-count {
    display: inline-block;
    margin-left: 8px;
    color: var(--td-text-color-secondary);
  }
}

.search-input {
  width: 360px;
}

.t-button + .t-button {
  margin-left: @spacer;
}
</style>
